package com.ddy.test.inputStream;

import java.io.*;

/**
 * Created by ddy on 2017/12/13.
 */
public class FileReader {

    public static void main(String[] args) {
        readInputStreamFromTxt("/Volumes/NO NAME/点读课本/BookCode.nst");
    }

    public static void mainTest(String[] args) {
        String filePath = "/Users/ddy/Documents/yun-顺义/sy002-users.txt";
        StringBuffer stringBuffer = new StringBuffer();
        read(filePath, stringBuffer);

    }

    public static String readStringFromTxt(String filePath){
        if(null == filePath || "".equals(filePath)){
            return null;
        }
        File file = new File(filePath);
        if(!file.exists()){
            return null;
        }
        StringBuffer stringBuffer = new StringBuffer();
        read(filePath, stringBuffer);
        return stringBuffer.toString();
    }

    public static void read(String filePath, StringBuffer stringBuffer) {
        try {
            InputStream is = new FileInputStream(filePath);
            InputStreamReader reader = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(reader);
            String line = "";
            while (line != null) {
                stringBuffer.append(line);
                line = br.readLine(); // 一次读入一行数据
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static InputStream readInputStreamFromTxt(String filePath){
        if(null == filePath || "".equals(filePath)){
            return null;
        }
        File file = new File(filePath);
        if(!file.exists()){
            return null;
        }
        try {
            InputStream is = new FileInputStream(filePath);
            byte[] bytes = new byte[2048];
            int read = is.read(bytes);
            System.out.println(new String(bytes));
            return is;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
